import 'dart:async';

import 'package:get/get.dart';
import 'package:mziot/app/data/device_group_entity.dart';
import 'package:mziot/app/data/device_info_entity.dart';
import 'package:mziot/app/data/device_list_entity.dart';
import 'package:mziot/app/data/group_info_entity.dart';
import 'package:mziot/app/modules/devices/device_provider.dart';
import 'package:mziot/app/routes/app_pages.dart';
import 'package:mziot/app/tools/blue_service.dart';
import 'package:mziot/app/tools/tools.dart';

class LightingController extends GetxController {
  DeviceProvider provider = DeviceProvider();
  DeviceListList? unitDevice;
  DeviceGroupList? unitGroup;
  Timer? _timer;
  var name = ''.obs;
  var isLock = false.obs;
  var isWifi = false.obs;
  var isBluetooth = false.obs;
  var isClose = false.obs;
  var isGroup = false;
  var oldLight = 0.obs;
  var currentLight = 0.obs;
  var uploadLight = 0.obs;
  var uploadClose = false;
  final isLoading = false.obs;
  var isNet = false;

  Rx<DeviceInfoEntity?> deviceInfoEntity = null.obs;
  Rx<GroupInfoEntity?> groupInfoEntity = null.obs;

  @override
  void onInit() {
    super.onInit();
    logger.v('Get.arguments ${Get.arguments}');
    if (Get.arguments is DeviceListList) {
      unitDevice = Get.arguments;
      name.value = unitDevice?.deviceName ?? '';
      isLock.value = unitDevice?.isLock.value ?? false;
      isWifi.value = unitDevice?.isWifi.value ?? false;
      isBluetooth.value = unitDevice?.isBluetooth.value ?? false;
      isClose.value = unitDevice?.closeState.value ?? false;
      isGroup = false;
      var rate = unitDevice?.lightRate.value ?? 0;
      if (rate < 0) {
        rate = 0;
      }
      oldLight.value = rate;
    }
    if (Get.arguments is DeviceGroupList) {
      unitGroup = Get.arguments;
      name.value = unitGroup?.groupName ?? '';
      isLock.value = unitGroup?.lockStatus ?? false;
      isClose.value = unitGroup?.isClose ?? false;
      isGroup = true;
      var rate = 0;
      if (isLock.value) {
        rate = unitGroup?.sceneLightRate ?? 0;
      } else {
        rate = unitGroup?.groupLightRate ?? 0;
      }
      if (rate < 0) {
        rate = 0;
      }
      oldLight.value = rate;
    }
    currentLight.value = oldLight.value;
    uploadClose = !isClose.value;
  }

  @override
  void onReady() {
    super.onReady();

    if (unitDevice != null) {
      listenData();
    } else {
      fetchGroupInfo();
    }
  }

  void listenData() {
    _timer?.cancel();
    _timer = null;
    _timer = Timer.periodic(Duration(seconds: 3), (timer) async {
      if (Get.currentRoute != Routes.LIGHTING) {
        return;
      }

      final index =
          BlueService.share.deviceList.indexWhere((element) => element.id == unitDevice!.id);
      if (index != -1 && isNet) {
        final info = BlueService.share.deviceList[index];
        isWifi.value = info.isWifi.value;
        isBluetooth.value = info.isBluetooth.value;
        currentLight.value = info.lightRate.value;
        isClose.value = info.closeState.value;
        uploadClose = !isClose.value;
      }
      isNet = true;
    });
  }

  void fetchGroupInfo() {
    provider.takeGroupInfo(unitGroup!.id!).then((value) {
      if (value.isSuccess) {
        isLock.value = value.data?.sceneLockStatus ?? false;
        isClose.value = value.data?.isClose ?? false;
        var rate = 0;
        rate = value.data?.lightRate ?? 0;
        if (rate < 0) {
          rate = 0;
        }
        oldLight.value = rate;
      }
      currentLight.value = oldLight.value;
      uploadClose = !isClose.value;
    });
  }

  //开关控制
  void openAction() async {
    if (isLock.value && !isWifi.value && !isGroup) {
      return;
    }
    if (isLock.value && isGroup) {
      return;
    }
    fetchSwitchDevices();
  }

  void fetchLightDevices() {
    isLoading.value = true;
    provider
        .lightingDevices(id: unitDevice?.id, light: uploadLight.value, groupId: unitGroup?.id)
        .then((value) async {
      if (value.isSuccess) {
        currentLight.value = uploadLight.value;
        await BlueService.share.execCmds(value.data);
        isNet = false;
      } else {
        currentLight.value = oldLight.value;
      }
      showToast(value.msg ?? '');
    }).whenComplete(() {
      isLoading.value = false;
    });
  }

  void fetchSwitchDevices() {
    isLoading.value = true;
    provider
        .switchDevices(
      isClose: uploadClose,
      id: unitDevice?.id,
      groupId: unitGroup?.id,
    )
        .then((value) async {
      if (value.isSuccess) {
        isClose.value = uploadClose;
        uploadClose = !uploadClose;
        await BlueService.share.execCmds(value.data);
        isNet = false;
      }
      showToast(value.msg ?? '');
    }).whenComplete(() {
      isLoading.value = false;
    });
  }

  @override
  void onClose() {
    _timer?.cancel();
    _timer = null;
  }
}
